<template>
    <div id="access" ref="accessWrapper">
        <AButton
            @click="
                operationType = 'create';
                state.formData = { ...initFormData };
                modalVisible = true;
            "
            type="primary"
            shape="circle"
        >
            <template #icon>
                <PlusOutlined />
            </template>
        </AButton>
        <ATable
            v-if="state.dataSource.length"
            :scroll="{ y: tableScrollY, x: 1920 }"
            :pagination="false"
            :columns="columns"
            :dataSource="state.dataSource.map((item, index) => ({ ...item, key: index }))"
            :expandRowByClick="true"
            :defaultExpandAllRows="true"
        >
            <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'type'">
                    <ATag v-if="record.type === 1">模块</ATag>
                    <ATag v-if="record.type === 2" color="success">菜单</ATag>
                    <ATag v-if="record.type === 3" color="cyan">操作</ATag>
                </template>
                <template v-if="column.dataIndex === 'operation'">
                    <div @click.stop>
                        <AButton
                            @click="
                                operationType = 'update';
                                state.formData = { ...record, status: record.status ? true : false };
                                state.updatedRecord = record;
                                modalVisible = true;
                            "
                            type="primary"
                            >编辑</AButton
                        >
                        <APopconfirm @confirm="handleDelete(record)" :title="`确定删除${record.module_name}吗？`">
                            <AButton type="danger">删除</AButton>
                        </APopconfirm>
                    </div>
                </template>
            </template>
        </ATable>
        <ATable v-else :dataSource="[]" :columns="columns" />
        <AModal @ok="confirmForm" v-model:visible="modalVisible" :title="`${operationType === 'create' ? '添加' : '编辑'}`" :width="600">
            <ARow>
                <ACol span="21">
                    <AForm @finish="confirmForm" ref="formRef" :model="state.formData" v-bind="{ labelCol: { span: 6 }, wrapperCol: { span: 18 } }">
                        <AFormItem name="module_name" label="模块名">
                            <AInput v-model:value="state.formData.module_name" placeholder="请输入模块名" />
                        </AFormItem>
                        <AFormItem name="action_name" label="操作名">
                            <AInput v-model:value="state.formData.action_name" placeholder="请输入操作名" />
                        </AFormItem>
                        <AFormItem name="type" label="类型">
                            <ASelect v-model:value="state.formData.type">
                                <ASelectOption :value="1">模块</ASelectOption>
                                <ASelectOption :value="2">菜单</ASelectOption>
                                <ASelectOption :value="3">操作</ASelectOption>
                            </ASelect>
                        </AFormItem>
                        <AFormItem name="url" label="操作地址">
                            <AInput v-model:value="state.formData.url" placeholder="请输入操作地址" />
                        </AFormItem>
                        <AFormItem name="method" label="请求类型">
                            <ASelect v-model:value="state.formData.method">
                                <ASelectOption value="">--空--</ASelectOption>
                                <ASelectOption value="GET">GET</ASelectOption>
                                <ASelectOption value="POST">POST</ASelectOption>
                                <ASelectOption value="DELETE">DELETE</ASelectOption>
                                <ASelectOption value="PATCH">PATCH</ASelectOption>
                                <ASelectOption value="PUT">PUT</ASelectOption>
                                <ASelectOption value="HEAD">HEAD</ASelectOption>
                                <ASelectOption value="OPTIONS">OPTIONS</ASelectOption>
                            </ASelect>
                        </AFormItem>
                        <AFormItem name="module_id" label="所属模块">
                            <ASelect v-model:value="state.formData.module_id">
                                <ASelectOption value="0">--顶级模块--</ASelectOption>
                                <ASelectOption v-for="(item, index) in state.dataSource" :key="index" :value="item._id">{{ item.module_name }}</ASelectOption>
                            </ASelect>
                        </AFormItem>
                        <AFormItem name="sort" label="排序号">
                            <AInput type="number" v-model:value="state.formData.sort" placeholder="请输入排序号" />
                        </AFormItem>
                        <AFormItem name="description" label="描述">
                            <ATextarea :rows="3" v-model:value="state.formData.description" placeholder="请输入描述" />
                        </AFormItem>
                        <AFormItem name="status" label="权限状态">
                            <ASwitch v-model:checked="state.formData.status" checkedChildren="可用" unCheckedChildren="禁用" />
                        </AFormItem>
                    </AForm>
                </ACol>
                <ACol span="3"> </ACol>
            </ARow>
        </AModal>
    </div>
</template>

<script setup>
import { PlusOutlined } from "@ant-design/icons-vue";
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import { createAccessApi, deleteAccessApi, getAccessApi, updateAccessApi } from "@/api/access";
import { message } from "ant-design-vue";
import { useStore } from "vuex";
const store = useStore();
const initFormData = {
    module_name: "",
    action_name: "",
    type: 1,
    url: "",
    method: "",
    module_id: "0",
    sort: 100,
    description: "",
    status: true,
};
const state = reactive({
    dataSource: [],
    formData: { ...initFormData },
    updatedRecord: {},
});
const columns = [
    {
        dataIndex: "module_name",
        title: "模块名",
        width: 1,
        fixed: "left",
    },
    {
        dataIndex: "action_name",
        title: "操作名",
        width: 1,
    },
    {
        dataIndex: "type",
        title: "节点类型",
        width: 1,
        customRender: ({ text }) => {
            switch (text) {
                case 1:
                    return "模块";
                case 2:
                    return "菜单";
                case 3:
                    return "操作";
                default:
                    return "";
            }
        },
    },
    {
        dataIndex: "url",
        title: "操作地址",
        width: 1.5,
    },
    {
        dataIndex: "method",
        title: "请求方法",
        width: 0.7,
    },
    {
        dataIndex: "module_id",
        title: "所属模块",
        width: 1,
        customRender: ({ text }) => {
            if (text === "0") return "--顶级模块--";
            const parentModule = state.dataSource.find(item => item._id === text);
            return parentModule ? parentModule.module_name : "";
        },
    },
    {
        dataIndex: "sort",
        title: "排序号",
        width: 1,
    },
    {
        dataIndex: "description",
        title: "描述",
        width: 1,
    },
    {
        dataIndex: "status",
        title: "状态",
        width: 1,
        customRender: ({ text }) => (text ? "可用" : "不可用"),
    },
    {
        dataIndex: "_id",
        title: "ID",
        width: 2,
    },
    {
        title: "操作",
        width: 1.3,
        dataIndex: "operation",
        fixed: "right",
    },
];

const modalVisible = ref(false);
const operationType = ref("create");
const formRef = ref();
const getAccess = () => {
    return getAccessApi().then(res => {
        if (res.code === 200) {
            state.dataSource = res.data;
        }
    });
};
getAccess();
const confirmForm = () => {
    formRef.value.validate().then(result => {
        const body = { ...result, status: result.status ? 1 : 0 };
        if (operationType.value === "create") {
            createAccessApi(body).then(async res => {
                if (res.code === 200) {
                    await getAccess();
                    await store.dispatch("getMenu");
                    message.success("添加成功");
                    modalVisible.value = false;
                }
            });
        }
        if (operationType.value === "update") {
            updateAccessApi({ _id: state.updatedRecord._id, ...result }).then(async res => {
                if (res.code === 200) {
                    await getAccess();
                    await store.dispatch("getMenu");
                    message.success("更新成功");
                    modalVisible.value = false;
                }
            });
        }
    });
};
const handleDelete = record => {
    deleteAccessApi({ _id: record._id }).then(async res => {
        if (res.code === 200) {
            await getAccess();
            await store.dispatch("getMenu");
            message.success("删除成功");
        }
    });
};
const accessWrapper = ref();
const tableScrollY = ref(0);
const calcScrollY = () => {
    tableScrollY.value = accessWrapper.value.offsetHeight - 64;
};
onMounted(() => {
    calcScrollY();
});
window.addEventListener("resize", e => {
    calcScrollY();
});
</script>

<style scoped lang="scss">
#access {
    width: 100%;
    height: 100%;
}
</style>
